<?php
require_once dirname(__FILE__) . '/Database.class.php';
global $dbConn;
connect();
global $tablesArray;

/**
 * 获取DB对象
 *
 * @param string $tablename
 *            表名字
 * @return Database db对象
 */
function T($tablename)
{
    global $tablesArray;
    if (isset($tablesArray[$tablename])) {
        return $tablesArray[$tablename];
    }
    return false;
}

/**
 *
 * @param string $tablename
 *            表名字
 * @param Database $dbobj
 */
function registerTable($tablename, $dbobj)
{
    global $tablesArray;
    $tablesArray[$tablename] = $dbobj;
}

function connect()
{
    global $_GCONFIG;
    connectTo($_GCONFIG["db"]["host"], $_GCONFIG["db"]["user"], $_GCONFIG["db"]["passwd"], $_GCONFIG["db"]["dbname"]);
}

function connectTo($host, $username, $password, $dbname)
{
    try {
        global $dbConn;
        
        $dbConn = new mysqli($host, $username, $password, $dbname);
        if ($dbConn->connect_errno) {
            die("数据库链接失败：" . $dbConn->connect_error);
        }
        $dbConn->select_db($dbname) or die("选择数据库失败：" . $dbConn->error);
        $dbConn->set_charset("utf8") or die("设置字符集失败：" . $dbConn->error);
      
    } catch (Exception $e) {
        die("出现了未知错误：" . $e->__toString());
    }
}

function getConnection()
{
    global $dbConn;
    return $dbConn;
}

function query($sql)
{
    global $dbConn;
    $result = $dbConn->query($sql);
    addQueryTotal();
    if (! $result) {
        debug();
        printf("Error: %s\n", $dbConn->error);
        exit();
    }
    return $result;
}
?>
